import React from "react";

let checkPermissionCodeFunc: TPermissionCheckFunc;

export type TPermissionCheckFunc = (permissionCode?: string | string[]) => boolean | undefined;

export function initPermissionCheckFunction(func: TPermissionCheckFunc) {
  checkPermissionCodeFunc = func;
}

export function checkPermission(permissionCode?: string | string[]) {
  if (!permissionCode || !checkPermissionCodeFunc) {
    return true;
  }
  return checkPermissionCodeFunc(permissionCode);
}

export default function withPermission<C, T>(WrappedComponent: React.ComponentType<T>) {

  return class NewWappedComponent extends React.Component<T & { permissionCode?: string | string[]; useHide?: boolean }> {
    render() {
      const extra: any = {...this.props};
      const {permissionCode} = this.props;
      let hasPrivilege = true;
      if (permissionCode) {
        if (!checkPermission(permissionCode)) {
          extra.disabled = true;
          hasPrivilege = false;
        }
      }

      // 不能直接用disabled属性判断，因为disable状态有可能是页面传递进来的
      if (!hasPrivilege && extra.useHide) {
        return null;
      }

      delete extra.useHide;
      delete extra.permissionCode;
      return <WrappedComponent {...extra} />;
    }
  };
}
